<template>
  <div class="emergency-end-node">
    <div class="node-header">
      <h3 class="node-title">应急终止</h3>
      <div class="button-group">
        <el-tag type="info" v-if="evaluationList.length > 0">{{ evaluationInfoText }}</el-tag>
        <el-button type="success" @click="handleSaveEvaluation" v-if="!isCompleted">保存评估</el-button>
        <el-button type="primary" @click="$emit('next-step')" v-if="!isCompleted">
          完成终止
        </el-button>
        <el-button v-if="evaluationList.length > 1" @click="loadNextEvaluation">查看下一条</el-button>
        <el-button type="info" @click="toggleEditMode">{{ isEditing ? '切换到非编辑模式' : '切换到编辑模式' }}</el-button>
      </div>
    </div>

    <!-- 事件详情 -->
    <div class="event-details-section">
      <div class="section-title">事件详情</div>
      <el-descriptions border :column="2">
        <el-descriptions-item label="事件编号">{{ eventData.id }}</el-descriptions-item>
        <el-descriptions-item label="发生地点">{{ eventData.location }}</el-descriptions-item>
        <el-descriptions-item label="事件描述" :span="2">{{ eventData.description }}</el-descriptions-item>
        <el-descriptions-item label="发生时间">{{ formatDateTime(eventData.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="持续时间">{{ getDuration() }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <!-- 评估表单 -->
    <div class="evaluation-section">
      <div class="section-title">处置效果评估</div>
      <el-form ref="evaluationFormRef" :model="evaluationForm" :rules="evaluationRules" label-width="120px" :disabled="isCompleted || !isEditing">
        <el-form-item label="评估部门" prop="deptId">
          <el-input v-model="evaluationForm.deptId" placeholder="请输入评估部门" />
        </el-form-item>
        <el-form-item label="评估时间" prop="evaluationTime">
          <el-date-picker
            v-model="evaluationForm.evaluationTime"
            type="datetime"
            placeholder="选择评估时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            class="w-full"
          />
        </el-form-item>
        
        <!-- 评分表格 -->
        <div class="score-table-title">评分项目</div>
        <el-table v-if="isEditing" :data="scoreItems" border class="score-table">
          <el-table-column prop="content" label="评分维度" min-width="150" />
          <el-table-column prop="maxScore" label="最高分值" width="100" align="center" />
          <el-table-column prop="weight" label="权重" width="100" align="center">
            <template #default="{ row }">
              {{ (row.weight * 100).toFixed(0) }}%
            </template>
          </el-table-column>
          <el-table-column label="得分" width="150" align="center">
            <template #default="{ row }">
              <el-input-number 
                v-model="row.score" 
                :min="0" 
                :max="row.maxScore" 
                :precision="1"
                controls-position="right"
                @change="calculateTotalScore"
                :disabled="isCompleted || !isEditing"
              />
            </template>
          </el-table-column>
        </el-table>
        
        <div class="total-score-display">
          <span class="label">最终评分：</span>
          <span class="value" :class="getScoreClass(evaluationForm.totalScore)">{{ evaluationForm.totalScore }}分</span>
        </div>
        
        <el-form-item label="评估总结" prop="comments">
          <el-input
            type="textarea"
            v-model="evaluationForm.comments"
            :rows="4"
            placeholder="请输入评估总结和补充说明"
            :disabled="isCompleted || !isEditing"
          />
        </el-form-item>
      </el-form>
    </div>

    <!-- 提示信息 -->
    <div class="tip-section">
      <el-alert
        v-if="!isCompleted"
        title="完成评估后，点击'完成终止'进入后期处置阶段"
        type="info"
        :closable="false"
        show-icon
      />
      <el-alert
        v-else
        title="该事件已终止，评估信息不可编辑"
        type="info"
        :closable="false"
        show-icon
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, defineProps, defineEmits, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import dayjs from 'dayjs';
import duration from 'dayjs/plugin/duration';
import { 
  getDisposalEvaluationList,
  getDisposalEvaluationDetail,
  addDisposalEvaluation, 
  updateDisposalEvaluation, 
  getEvaluationRuleList 
} from "@/api/bridge/command/evaluation";

dayjs.extend(duration);

const props = defineProps({
  eventData: {
    type: Object,
    required: true
  }
});

defineEmits(['next-step']);

// 终止时间默认为当前时间
const endTime = dayjs().format('YYYY-MM-DD HH:mm:ss');

// 判断是否已完成（不允许编辑）
const isCompleted = computed(() => {
  return props.eventData && props.eventData.flowStatus >= 4;
});

// 评估列表
const evaluationList = ref<any[]>([]);
const currentEvaluationIndex = ref(0);

// 显示评估信息
const evaluationInfoText = computed(() => {
  if (evaluationList.value.length > 0) {
    return `共 ${evaluationList.value.length} 条评估，当前第 ${currentEvaluationIndex.value + 1} 条`;
  }
  return '暂无评估';
});

// 评估表单
const evaluationFormRef = ref();
const evaluationForm = ref({
  id: "",
  eventId: "",
  deptId: "",
  evaluationTime: dayjs().format("YYYY-MM-DD HH:mm:ss"),
  totalScore: 0,
  comments: "",
  scoreItems: []
});

// 评分项数据
const scoreItems = ref([]);

// 表单校验规则
const evaluationRules = {
  deptId: [{ required: true, message: "请输入评估部门", trigger: "blur" }],
  evaluationTime: [{ required: true, message: "请选择评估时间", trigger: "change" }],
  comments: [{ required: true, message: "请输入评估总结", trigger: "blur" }]
};

// 计算事件持续时间
const getDuration = () => {
  if (!props.eventData.startTime) return '-';
  const start = dayjs(props.eventData.startTime);
  const end = dayjs(endTime);
  const diff = dayjs.duration(end.diff(start));
  
  const days = diff.days();
  const hours = diff.hours();
  const minutes = diff.minutes();
  
  let result = '';
  if (days > 0) result += `${days}天`;
  if (hours > 0 || days > 0) result += `${hours}小时`;
  result += `${minutes}分钟`;
  
  return result;
};

// 格式化日期时间
const formatDateTime = (date) => {
  if (!date) return '-';
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss');
};

// 获取评分样式
const getScoreClass = (score) => {
  if (!score) return 'score-low';
  score = parseFloat(score);
  if (score >= 80) return 'score-high';
  if (score >= 60) return 'score-medium';
  return 'score-low';
};

// 加载下一条评估
const loadNextEvaluation = () => {
  if (evaluationList.value.length <= 1) return;
  
  currentEvaluationIndex.value = (currentEvaluationIndex.value + 1) % evaluationList.value.length;
  const nextEvaluation = evaluationList.value[currentEvaluationIndex.value];
  loadEvaluationDetail(nextEvaluation.id);
};

// 获取评估列表
const fetchEvaluationList = async () => {
  try {
    if (!props.eventData || !props.eventData.id) return;
    
    const params = {
      eventId: props.eventData.id,
      pageNum: 1,
      pageSize: 10
    };
    
    const res = await getDisposalEvaluationList(params);
    if (res.code === 200) {
      evaluationList.value = res.rows || [];
      
      // 如果有评估，显示第一条
      if (evaluationList.value.length > 0) {
        currentEvaluationIndex.value = 0;
        await loadEvaluationDetail(evaluationList.value[0].id);
      } else {
        // 如果没有评估，初始化评分项
        await initScoreItems();
      }
    }
  } catch (error) {
    console.error('获取评估列表失败:', error);
  }
};

// 加载评估详情
const loadEvaluationDetail = async (id) => {
  try {
    const res = await getDisposalEvaluationDetail(id);
    if (res.code === 200) {
      evaluationForm.value = {
        ...res.data,
        evaluationTime: res.data.evaluationTime ? dayjs(res.data.evaluationTime).format('YYYY-MM-DD HH:mm:ss') : dayjs().format('YYYY-MM-DD HH:mm:ss')
      };
      
      // 初始化评分项
      await initScoreItems();
      
      // 如果有历史评分数据，填充到表格中
      if (res.data.scoreItems && res.data.scoreItems.length > 0) {
        res.data.scoreItems.forEach(item => {
          const index = scoreItems.value.findIndex(i => i.ruleId === item.ruleId);
          if (index !== -1) {
            scoreItems.value[index].score = item.score;
          }
        });
      }
      
      calculateTotalScore();
    }
  } catch (error) {
    console.error('获取评估详情失败:', error);
  }
};

// 初始化评分项
const initScoreItems = async () => {
  try {
    const res = await getEvaluationRuleList({
      pageNum: 1,
      pageSize: 1000,
      status: 1 // 只获取启用状态的规则
    });
    
    if (res.code === 200) {
      scoreItems.value = res.rows.map(rule => ({
        ruleId: rule.id,
        content: rule.content,
        maxScore: rule.maxScore,
        weight: rule.weight,
        score: 0
      }));
    } else {
      // 如果获取失败，使用默认评分项
      scoreItems.value = [
        { ruleId: '1', content: '处置及时性', maxScore: 10, weight: 0.2, score: 0 },
        { ruleId: '2', content: '信息传递准确性', maxScore: 10, weight: 0.2, score: 0 },
        { ruleId: '3', content: '资源调配效率', maxScore: 10, weight: 0.2, score: 0 },
        { ruleId: '4', content: '协作配合水平', maxScore: 10, weight: 0.2, score: 0 },
        { ruleId: '5', content: '预期目标达成度', maxScore: 10, weight: 0.2, score: 0 }
      ];
    }
  } catch (error) {
    console.error('获取评分规则失败:', error);
    // 使用默认评分项
    scoreItems.value = [
      { ruleId: '1', content: '处置及时性', maxScore: 10, weight: 0.2, score: 0 },
      { ruleId: '2', content: '信息传递准确性', maxScore: 10, weight: 0.2, score: 0 },
      { ruleId: '3', content: '资源调配效率', maxScore: 10, weight: 0.2, score: 0 },
      { ruleId: '4', content: '协作配合水平', maxScore: 10, weight: 0.2, score: 0 },
      { ruleId: '5', content: '预期目标达成度', maxScore: 10, weight: 0.2, score: 0 }
    ];
  }
};

// 计算总分
const calculateTotalScore = () => {
  if (scoreItems.value.length === 0) return 0;
  if(!isEditing.value) return ;
  let totalScore = 0;
  for (const item of scoreItems.value) {
    totalScore += (item.score * item.weight);
  }
  
  evaluationForm.value.totalScore = parseFloat(totalScore.toFixed(2));
};

// 保存评估
const handleSaveEvaluation = async () => {
  if (!evaluationFormRef.value) return;
  
  await evaluationFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 设置事件ID
        evaluationForm.value.eventId = props.eventData.id;
        
        // 组装提交数据
        const submitData = { 
          ...evaluationForm.value,
          scoreItems: scoreItems.value.map(item => ({
            ruleId: item.ruleId,
            score: item.score
          }))
        };
        
        // 根据是否有ID决定是新增还是更新
        const hasId = !!evaluationForm.value.id;
        const actionApi = hasId ? updateDisposalEvaluation : addDisposalEvaluation;
        const res = await actionApi(submitData);
        
        if (res.code === 200) {
          ElMessage.success(hasId ? '评估更新成功' : '评估保存成功');
          
          // 如果是新增，设置返回的ID
          if (!hasId && res.data) {
            evaluationForm.value.id = res.data.id;
          }
          
          // 重新获取评估列表
          await fetchEvaluationList();
        } else {
          ElMessage.error(res.msg || '保存失败');
        }
      } catch (error) {
        console.error('保存评估失败:', error);
        ElMessage.error('保存失败');
      }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

const isEditing = ref(false);

const toggleEditMode = () => {
  isEditing.value = !isEditing.value;
};

onMounted(async () => {
  // 设置事件ID
  if (props.eventData && props.eventData.id) {
    evaluationForm.value.eventId = props.eventData.id;
    await fetchEvaluationList();
  } else {
    await initScoreItems();
  }
});
</script>

<style scoped lang="scss">
.emergency-end-node {
  padding: 20px;
  
  .node-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 24px;
    
    .node-title {
      font-size: 18px;
      font-weight: 600;
      margin: 0;
      color: var(--el-text-color-primary);
    }
    
    .button-group {
      display: flex;
      gap: 12px;
      align-items: center;
    }
  }
  
  .section-title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 16px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 8px;
      border-radius: 2px;
    }
  }
  
  .event-details-section,
  .evaluation-section {
    margin-bottom: 24px;
    padding: 20px;
    background-color: var(--el-bg-color-overlay);
    border-radius: 4px;
    box-shadow: var(--el-box-shadow-light);
  }
  
  .w-full {
    width: 100%;
  }
  
  .tip-section {
    margin-top: 20px;
  }
  
  /* 评分相关样式 */
  .score-table-title {
    font-size: 16px;
    font-weight: 600;
    margin: 20px 0 10px;
    color: var(--el-text-color-primary);
    display: flex;
    align-items: center;
    
    &::before {
      content: '';
      display: inline-block;
      width: 4px;
      height: 16px;
      background-color: var(--el-color-primary);
      margin-right: 8px;
      border-radius: 2px;
    }
  }
  
  .score-table {
    margin-bottom: 20px;
    
    :deep(.el-input-number) {
      width: 120px;
    }
  }
  
  .total-score-display {
    margin: 20px 0;
    padding: 15px;
    background-color: var(--el-fill-color-light);
    border-radius: 4px;
    display: flex;
    align-items: center;
    
    .label {
      font-size: 16px;
      font-weight: 600;
      margin-right: 10px;
    }
    
    .value {
      font-size: 24px;
      font-weight: 700;
    }
  }
  
  /* 评分颜色 */
  .score-high {
    color: var(--el-color-success);
  }
  
  .score-medium {
    color: var(--el-color-warning);
  }
  
  .score-low {
    color: var(--el-color-danger);
  }
}
</style> 